package com.bristua.barcode.supplier.controller;

import com.bristua.barcode.common.bean.Result;
import com.bristua.barcode.common.exception.BizException;
import com.bristua.barcode.common.util.HandleResultUtil;
import com.bristua.barcode.common.util.QRCodeUtil;
import com.bristua.barcode.supplier.enums.SupplierCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;

/**
 * Created by Administrator on 2019/8/5 0005.
 */
@RestController
@RequestMapping("supplier")
public class AnalysisQRCodeController {
    private static final Logger logger = LoggerFactory.getLogger(AnalysisQRCodeController.class);
    @Value("${filePath}")
    private String filePath;
    @RequestMapping("/file/analysis")
    public Result analysisQRCode(@RequestParam(value = "file") MultipartFile file){
        long  startTime=System.currentTimeMillis();
        String path=filePath+new Date().getTime()+file.getOriginalFilename();

        File newFile=new File(path);
        //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
        try {
            file.transferTo(newFile);
        }catch (Exception ex){
            logger.error("图片上传异常",ex);
            throw new BizException(SupplierCode.QR_CODE_IMG_UPLOAD_FAIL.getCode(),SupplierCode.QR_CODE_IMG_UPLOAD_FAIL.getMsg(),ex);
        }
        try {
            return HandleResultUtil.dataResult(SupplierCode.ANALYSIS_SUCCESS.getCode(),SupplierCode.ANALYSIS_SUCCESS.getMsg(),QRCodeUtil.decode(newFile));
        }catch (Exception ex){
            logger.error("二维码解析异常",ex);
            throw new BizException(SupplierCode.QR_CODE_ANALYSIS_EXCEPTION.getCode(),SupplierCode.QR_CODE_ANALYSIS_EXCEPTION.getMsg(),ex);
        }
    }
}
